package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.vo.PicUploadResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

@Service
public class UserInfoService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private PicUploadService picUploadService;

    public boolean saveUserInfo(Map<String, String> param, String token) {
        // 校验token
        User user = userService.queryUserByToken(token);

        if (null == user) {
            return false;
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equalsAnyIgnoreCase(param.get("gender"), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setSex(StringUtils.equalsAnyIgnoreCase(param.get("gender"), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setNickName(param.get("nickname"));
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setCity(param.get("city"));

        // 插入到数据库
        return userInfoMapper.insert(userInfo) == 1;
    }

    public boolean saveUserLogo(MultipartFile file, String token) {
        // 校验token
        User user = userService.queryUserByToken(token);

        // 校验是否是人像
        // TODO 由于虹软没有mac版本SDK,无法实现人脸识别功能,这里默认所有上传图片都被识别为头像.

        // 图片上传到aliyunOSS
        PicUploadResult fileUploadResult = picUploadService.upload(file);

        if (StringUtils.isEmpty(fileUploadResult.getName())) {
            // 上传失败
            return false;
        }

        // 走到这里,即上传成功,我们把头像保存到信息表中
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(fileUploadResult.getName());

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        int update = userInfoMapper.update(userInfo, queryWrapper);

        return update == 1;
    }
}
